<?php

namespace Medicina\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Medicina\KernelBundle\Entity\Role;
use Medicina\BackendBundle\Form\RoleType;

/**
 * Role controller.
 *
 */
class RoleController extends Controller {

    /**
     * Lists all Role entities.
     *
     */
    public function indexAction() {
        $entity = new Role();
        $em = $this->getDoctrine()->getEntityManager();
        $paginador = $this->get('ideup.simple_paginator');
        $paginador->setItemsPerPage(10);
        $request = $this->getRequest();
        $roles = $em->getRepository('MedicinaKernelBundle:Role')->findAll();
        $entities = $paginador->paginate($roles)->getResult();

        return $this->render('BackendBundle:Role:index.html.twig', array(
                    'entities' => $entities,
                    'paginador' => $paginador,
                    'delete_form' => $this->createDeleteForm()->createView()
                ));
    }

    /**
     * Finds and displays a Role entity.
     *
     */
    public function showAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Role')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se ha encontrado la role solicitada');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BackendBundle:Role:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Displays a form to create a new Role entity.
     *
     */
    public function newAction() {
        $entity = new Role();
        $form = $this->createForm(new RoleType(), $entity);

        return $this->render('BackendBundle:Role:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView()
                ));
    }

    /**
     * Creates a new Role entity.
     *
     */
    public function createAction() {
        $entity = new Role();
        $request = $this->getRequest();
        $form = $this->createForm(new RoleType(), $entity);
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            try {

                $em->persist($entity);
                $em->flush();
                $this->get('session')->setFlash('notice', 'Se guardo el nuevo Rol correctamente');

                return $this->redirect($this->generateUrl('role', array('id' => $entity->getId())));
            } catch (\PDOException $e) {
                $this->get('session')->setFlash('error', 'Ya existe un Rol con el mismo nombre');

                return $this->render('BackendBundle:Role:new.html.twig', array(
                            'entity' => $entity,
                            'form' => $form->createView()
                        ));
            }
        }
        $this->get('session')->setFlash('error', 'Ya existe un Rol con el mismo nombre');

        return $this->render('BackendBundle:Role:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView()
                ));
    }

    /**
     * Displays a form to edit an existing Role entity.
     *
     */
    public function editAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Role')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se ha encontrado la role solicitada');
        }

        $editForm = $this->createForm(new RoleType(), $entity);

        return $this->render('BackendBundle:Role:edit.html.twig', array(
                    'entity' => $entity,
                    'form' => $editForm->createView(),
                ));
    }

    /**
     * Edits an existing Role entity.
     *
     */
    public function updateAction($id) {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('MedicinaKernelBundle:Role')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se ha encontrado la role solicitada');
        }

        $editForm = $this->createForm(new RoleType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            try {

                $em->persist($entity);
                $em->flush();

                $this->get('session')->setFlash('notice', 'Rol actualizado con éxito');
                return $this->redirect($this->generateUrl('role'));
            } catch (\PDOException $e) {
                $this->get('session')->setFlash('error', 'Ya existe un rol con el nombre ingresado');

                return $this->render('BackendBundle:Role:edit.html.twig', array(
                            'entity' => $entity,
                            'form' => $editForm->createView(),
                            'delete_form' => $deleteForm->createView(),
                        ));
            }
        }
        $this->get('session')->setFlash('error', 'Ya existe un rol con el nombre ingresado');

        return $this->render('BackendBundle:Role:edit.html.twig', array(
                    'entity' => $entity,
                    'form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
    }

    /**
     * Deletes a Role entity.
     *
     */
    public function deleteAction($id) {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        //  if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('MedicinaKernelBundle:Role')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se ha encontrado la role solicitada');
        }
        try {
            $em->remove($entity);
            $em->flush();     //   }
            $this->get('session')->setFlash('notice', 'Se eliminó el rol correctamente');
        } catch (\PDOException $e) {
            $this->get('session')->setFlash('error', 'No se puede dar de baja el rol seleccionado: contiene información que esta siendo utilizada por usuarios del sistema');
        }
        return $this->redirect($this->generateUrl('role'));
    }

//
//    private function createDeleteForm($id) {
//        return $this->createFormBuilder(array('id' => $id))
//                        ->add('id', 'hidden')
//                        ->getForm()
//        ;
//    }

    private function createDeleteForm() {
        return $this->createFormBuilder()->getForm();
    }

}
